package com.sg.common.empty.web;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sg.activiti.service.MyActivitiService;
import com.sg.common.empty.core.ConditionRes;
import com.sg.common.empty.core.Conditions;
import com.sg.common.empty.core.Conditions2;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.core.Params;
import com.sg.common.empty.core.Params2;
import com.sg.common.empty.service.CfgService;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;

@Repository
@Controller
@RequestMapping(value = "/api")
public class ApiController {

	private Logger logger = Logger.getLogger(getClass());
	// final String SEPORATOR = System.getProperty("line.separator");
	@Autowired
	MyActivitiService myActivitiService;

	@Autowired
	CfgService service;

	@RequestMapping(value = "/{tb1}/{tb2}/select")
	@ResponseBody
	public Object select(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		ConditionRes cr = Conditions2.init(request,requestBody).buildCon();
		String oransql = Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("code", 2000);
		return map;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/list")
	@ResponseBody
	public Object find(HttpServletRequest request, @RequestBody Map<String, Object> requestBody) throws Exception {
		long s = System.currentTimeMillis();
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions2 condis = Conditions2.init(request, requestBody);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String orancsql = Constant.get(route + ".csql");
		String oransql = Constant.get(route + ".sql");
		orancsql = orancsql.replace("@conditions", cr.getSql()).replace("@orderby", sorts);
		oransql = oransql.replace("@conditions", cr.getSql()).replace("@orderby", sorts).replace("@limit", limit);

		List<Object> countList = service.queryBySql(orancsql, cr.getParams());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql, cr.getParams(), res.split(","));

		int count = ((BigInteger) countList.get(0)).intValue();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("total", count);
		map.put("code", 2000);
		long e = System.currentTimeMillis();
		System.out.println(e - s);
		return map;
	}
	
	
	@RequestMapping(value = "/nlm/meeting/list")
	@ResponseBody
	public Object findM(HttpServletRequest request, @RequestBody Map<String, Object> requestBody) throws Exception {
		long s = System.currentTimeMillis();
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions2 condis = Conditions2.init(request, requestBody);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();
		// 替换
		String orancsql = Constant.get(route + ".csql");
		String oransql = Constant.get(route + ".sql");
		List<String> dates = Constant.getRbList(requestBody, "date");
		String sql = "";
		if (dates != null && !dates.isEmpty()) {
			String startDate = dates.get(0);
			String endDate = dates.get(1);
			sql = " and ((startDate >= " + "\'" + startDate + "\'" + " and endDate >= " + "\'" + endDate + "\'" + " and"
					+ "\'" + endDate + "\'" + " >= startDate" + " ) or (startDate >= " + "\'" + startDate + "\'"
					+ " and endDate <= " + "\'" + endDate + "\'" + " ) or (startDate <= " + "\'" + startDate + "\'"
					+ " and" + "\'" + startDate + "\'" + " <= endDate" + " and endDate <= " + "\'" + endDate + "\'"
					+ " ) or (startDate <= " + "\'" + startDate + "\'" + " and endDate >= " + "\'" + endDate + "\'"
					+ " ))";
			System.out.println(sql);

		} /*
			 * else { orancsql = orancsql.replace("@conditions", cr.getSql()).replace(
			 * "@orderby", sorts); oransql = oransql.replace("@conditions", cr.getSql())
			 * .replace("@orderby", sorts).replace("@limit", limit); }
			 */
		orancsql = orancsql.replace("@conditions", cr.getSql()).replace("@sql", sql).replace("@orderby", sorts);
		oransql = oransql.replace("@conditions", cr.getSql()).replace("@sql", sql).replace("@orderby", sorts)
				.replace("@limit", limit);

		List<Object> countList = service.queryBySql(orancsql, cr.getParams());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql, cr.getParams(), res.split(","));
		int count = ((BigInteger) countList.get(0)).intValue();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("total", count);
		map.put("code", 2000);
		long e = System.currentTimeMillis();
		System.out.println(e - s);
		return map;
	}

	@RequestMapping(value = {"/{tb1}/{tb2}/fust","/{tb1}/{tb2}/colle"})
	@ResponseBody
	public Object findf(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions2 condis = Conditions2.init(request,requestBody);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();

		String oransql = Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql()).replace(
				"@orderby", sorts);

		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("code", 2000);
		return map;
	}
	
	@RequestMapping(value = "/{tb1}/{tb2}/add")
	@ResponseBody
	public Object add(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
		String route = (String) request.getAttribute("conf.route");

		String oransql = Constant.get(route + ".sql");
		List<String> sqlParams = Params2.init(request,requestBody,service).build();
		service.excuteBySql(oransql, sqlParams.toArray());

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> item = new HashMap<String, Object>();
		item.put("id", sqlParams.get(0));
		map.put("item", item);
		map.put("code", 2000);
		return map;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/update")
	@ResponseBody
	public Object up(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) {
		String route = (String) request.getAttribute("conf.route");
		String oransql = Constant.get(route + ".sql");
		List<String> sqlParams = Params2.init(request,requestBody,service).build();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			service.excuteBySql(oransql, sqlParams.toArray());
			map.put("code", 2000);
		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("code", 5030);
			map.put("msg", "更新发生内部错误，请联系管理员");
		}
		return map;
	}
	
	@RequestMapping(value = "/{tb1}/{tb2}/update3")
	@ResponseBody
	public Object update3(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) {
		String route = (String) request.getAttribute("conf.route");
		//enable 1:需处理，2：待交接       pasts（交接次数）①待处理→需交接（2）：白班，赋值1；夜班，赋值101   ②需交接→待处理（1）：赋值0
		String enable = requestBody.get("enable").toString();
		if(enable.equals("1")){
			requestBody.put("pasts", '0');
		}
		String oransql = Constant.get(route + ".sql");
		List<String> sqlParams = Params2.init(request,requestBody,service).build();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			service.excuteBySql(oransql, sqlParams.toArray());
			map.put("code", 2000);
		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("code", 5030);
			map.put("msg", "更新发生内部错误，请联系管理员");
		}
		return map;
	}


	@RequestMapping(value = "/{tb1}/{tb2}/delOne")
	@ResponseBody
	public Object delOne(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
		String route = (String) request.getAttribute("conf.route");

		String oransql = Constant.get(route + ".sql");
//		String ids = requestBody.get("ids").toString();
		List<String> sqlParams = Params2.init(request,requestBody,service).build();
		Map<String, Object> map = new HashMap<String, Object>();
		service.excuteBySql(oransql, sqlParams.toArray());
		map.put("code", 2000);
//		if (StringUtils.isNotEmpty(ids)) {
//			String[] split = StringUtils.split(ids, ",");
//			for (String id : split) {
//				service.excuteBySql(oransql, new String[] { id });
//			}
//			map.put("code", 2000);
//		}
		return map;
	}
	
	
	@RequestMapping(value = "/{tb1}/{tb2}/del")
	@ResponseBody
	public Object del(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
		String route = (String) request.getAttribute("conf.route");

		String oransql = Constant.get(route + ".sql");
		String ids = requestBody.get("ids").toString();
//		String id = requestBody.get("id").toString();
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(ids)) {
			String[] split = StringUtils.split(ids, ",");
			for (String id : split) {
				service.excuteBySql(oransql, new String[] {(String) FilterVal.init("currentMemberId", service).get2(), (String) FilterVal.init("currentTime", service).get2(), id });
			}
			map.put("code", 2000);
		}
		return map;
	}
	
	@RequestMapping(value = {"/{tb1}/{tb2}/total"})
	@ResponseBody
	public Object chart(HttpServletRequest request) throws Exception {
//		String route = (String) request.getAttribute("conf.route");
//		// TODO 如果有js，使用js确定使用哪个sql
//		Conditions condis = Conditions.init(request);
//		ConditionRes cr = condis.buildCon();
//		String sorts = condis.buildSorts();
//
//		String oransql = Constant.get(route + ".sql");
//		oransql = oransql.replace("@conditions", cr.getSql()).replace(
//				"@orderby", sorts);

//		String res = Constant.get(route + ".res");
//		String daterangeSql = "select distinct daily from fs_order where payStatus='1' and DATEDIFF(now(),daily)<15";
		
//		List<Object> daterange = service.queryBySql(daterangeSql);
		List<Object> daterange = new ArrayList<Object>();
		for(int i =-15;i<0;i++){
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, i);
			String daily = DateTimeUtils.formatDate(calendar.getTime(), "yyyy-MM-dd");
			daterange.add(daily);
		}
		String dateSql = "";
		for(Object o:daterange){
			if(StringUtils.isEmpty(dateSql)){
				dateSql += "'"+ o +"'";
			}else{
				dateSql += ",'"+ o +"'";
			}
		}
		String totalOrderSql = "select daily,count(*) from fs_order where payStatus='1' and daily in ("+ dateSql +") group by daily";
		String lineOrderSql = "select daily,lindc,count(*) from fs_order where payStatus='1' and daily in ("+ dateSql +") group by daily,lindc";
//		String totalOrderSql = "select daily,count(*) from fs_order where payStatus='1' and DATEDIFF(now(),daily)<17 group by daily";
//		String lineOrderSql = "select daily,lindc,count(*) from fs_order where payStatus='1' and  DATEDIFF(now(),daily)<17 GROUP BY daily,lindc";
		
//		List<Map<String, Object>> total = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> totalMap = service.queryBySqlToMap(totalOrderSql, new String[]{"daily","count"});
		Map<String, Object> total = new HashMap<String, Object>();
		for(Map<String, Object> map :totalMap){
			total.put(map.get("daily").toString(),map.get("count"));
		}
		List<Map<String, Object>> lineOrder = service.queryBySqlToMap(lineOrderSql, new String[]{"daily","lindc","count"});
		
		Map<String, Object> line1Daily = new HashMap<>();
		Map<String, Object> line4Daily = new HashMap<>();
		Map<String, Object> line4bDaily = new HashMap<>();
		Map<String, Object> line2Daily = new HashMap<>();
		
		for(int i=0;i<daterange.size();i++){
			String daily = daterange.get(i).toString();
			for(Map<String, Object> mp: lineOrder){
				if(StringUtils.equals(daily, mp.get("daily").toString())){
					if(StringUtils.equals((String)mp.get("lindc"), "1号线")){
						line1Daily.put(daily, mp.get("count"));
					}else if(StringUtils.equals((String)mp.get("lindc"), "4号线")){
						line4Daily.put(daily, mp.get("count"));
					}else if (StringUtils.equals((String)mp.get("lindc"), "4号线支线")){
						line4bDaily.put(daily, mp.get("count"));
					}else if (StringUtils.equals((String)mp.get("lindc"), "2号线")){
						line2Daily.put(daily, mp.get("count"));
					}
				}
			}
		}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("daterange", daterange);
		data.put("total", total);
		data.put("line1", line1Daily);
		data.put("line4", line4Daily);
		data.put("line4b", line4bDaily);
		data.put("line2", line2Daily);

		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("items", dataList);{daterange:[],1:[],2:[]}
		map.put("items", data);
		map.put("code", 2000);
		return map;
	}
}